package com.mucd.blogblogs7000.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mucd.blog.annontion.NotNull;
import com.mucd.blog.entity.ArticleEntity;
import com.mucd.blog.result.R;
import com.mucd.blog.sentinel.ArrayRemoval;
import com.mucd.blogblogs7000.dao.BlogsDao;
import com.mucd.blogblogs7000.result.ArticleCountResult;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
@Log4j2
public class BlogsService {

    @Autowired
    private BlogsDao blogsDao;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;


    /**
     * 发布文章
     *
     * @param articleEntity
     * @return
     */

    public R save(ArticleEntity articleEntity) {

        //获取发布人
        String key = articleEntity.getArticleUsername();
        ValueOperations<String, Object> operations = redisTemplate.opsForValue();
        //发布人是否存在redis中
        Object key1 = operations.get(key);

        if (key1 == null) {
            //添加到数据库
            int insert = blogsDao.insert(articleEntity);
            if (insert <= 0) {
                return R.error("发布文章失败");
            }
            log.info("插入数据库");
            ////将发布人存入redis中（秒）
            operations.set(key, key, 5, TimeUnit.SECONDS);
        } else {
            //重新设置为5秒
            operations.set(key, key, 5, TimeUnit.SECONDS);
            log.info("重复请求");

        }

        return R.ok("发布成功");

    }


    /**
     * 删除文章
     *
     * @param articleId
     * @return
     */
    public R delete(List<Long> articleId) {
        int i = blogsDao.deleteBatchIds(articleId);
        if (i <= 0) {
            return R.error("删除文章失败");
        }
        return R.ok("删除成功");
    }

    /**
     * 修改文章
     *
     * @param articleEntity
     * @return
     */
    public R update(ArticleEntity articleEntity) {
        int i = blogsDao.updateById(articleEntity);
        if (i <= 0) {
            return R.error("修改文章失败");
        }
        return R.ok("修改成功");
    }


    /**
     * 分页查询文章
     *
     * @param page     当前页
     * @param pageSize 每页显示文章的条数
     * @return
     */
    public R select(Integer page, Integer pageSize) {

        Page<ArticleEntity> articleEntityPage = new Page<>(page, pageSize);
        QueryWrapper<ArticleEntity> QueryWrapper = new QueryWrapper<>();
        //排行正序      修改时间倒叙
        QueryWrapper.orderByAsc("article_ranking").orderByDesc("update_time");

        Page<ArticleEntity> Page = blogsDao.selectPage(articleEntityPage, QueryWrapper);
        return R.ok(Page);
    }

    /**
     * 获取用户博客下面的所有标签
     *
     * @param username
     * @return
     */
    public R getUserOfBlogsOfTags(String username) {
        QueryWrapper<ArticleEntity> QueryWrapper = new QueryWrapper<>();
        //查询用户所有状态为正常的文章
        List<ArticleEntity> list = blogsDao.selectList(QueryWrapper.eq("article_username", username).eq("article_status", 3));

        HashSet<String> hashSet = new HashSet<>();
        for (ArticleEntity articleEntity : list) {
            //获取所有标签
            String articleTags = articleEntity.getArticleTags();
            //将标签放入set集合中进行第一次去重
            hashSet.add(articleTags);
        }
        //第二次去重
        HashSet<String> removal = ArrayRemoval.removal(hashSet.toString());

        return R.ok(removal);
    }

    /**
     * 按照标签名获取文章信息
     *
     * @param username
     * @param tag
     * @return
     */
    public R getBlogsByTagName(String username, String tag) {
        QueryWrapper<ArticleEntity> QueryWrapper = new QueryWrapper<>();
        QueryWrapper.eq("article_username", username)
                .eq("article_status", 3)
                .like("article_tags", tag)
                .orderByDesc("update_time");

        List<ArticleEntity> list = blogsDao.selectList(QueryWrapper);
        return R.ok(list);
    }

    /**
     * 按照分类获取文章
     *
     * @param classify
     * @return
     */
    public R getArticleByClassify(String classify,String username) {
        QueryWrapper<ArticleEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("article_classify", classify);
        queryWrapper.eq("article_username", username);
        List<ArticleEntity> list = blogsDao.selectList(queryWrapper);
        return R.ok(list);
    }


    /**
     * 按照分类获取文章数量
     *
     * @return R
     */
    public R getArticleCountByClassify(@NotNull String username) {
        //所有文章
        List<ArticleEntity> list = blogsDao.selectList(null);
        //所有的分类
        Set<String> classify = new LinkedHashSet<>();

        List<ArticleCountResult> articleCount = new ArrayList<>();
        //将分类添加到集合
        for (ArticleEntity entity : list) {
            classify.add(entity.getArticleClassify());
        }

        //遍历分类
        for (String s : classify) {
            ArticleCountResult articleCountResult = new ArticleCountResult();
            //挑拣,每次查询的分类不一样
            QueryWrapper<ArticleEntity> qw = new QueryWrapper<>();
            qw.eq("article_classify", s);
            qw.eq("article_username", username);

            //获取查询到的count
            Integer count = blogsDao.selectCount(qw);

            //set到对象里
            articleCountResult.setName(s);
            articleCountResult.setValue(count);
            articleCount.add(articleCountResult);
        }

        return R.ok(articleCount);
    }
}
